<template>
  <div class="chat-home">
    <!-- 左侧聊天列表 -->
    <div class="chat-list">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchText"
          placeholder="搜索聊天记录"
          prefix-icon="Search"
          clearable
        />
      </div>

      <!-- 聊天列表 -->
      <div class="list-container">
        <div 
          v-for="chat in filteredChats"
          :key="chat.id"
          :class="['chat-item', { active: activeChat?.id === chat.id }]"
          @click="openChat(chat.id)"
        >
          <img :src="chat.avatar" class="avatar">
          <div class="info">
            <div class="header">
              <span class="name">{{ chat.name }}</span>
              <span class="time">{{ chat.lastTime }}</span>
            </div>
            <div class="preview">{{ chat.lastMessage }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-window">
      <!-- 嵌套路由出口 -->
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in">
          <component 
            :is="Component"
            :key="$route.params.chatId" 
          />
        </transition>
      </router-view>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const searchText = ref('')
// 模拟异步获取聊天列表
const chats = ref([])
const isLoading = ref(true)


// // 模拟聊天数据
// const chats = ref([
//   {
//     id: '123',
//     name: '张三',
//     avatar: '/avatars/1.jpg',
//     lastMessage: '今晚一起吃饭吗？',
//     lastTime: '10:30'
//   },
//   {
//     id: '456',
//     name: '李四',
//     avatar: '/avatars/2.jpg',
//     lastMessage: '项目文档已发送',
//     lastTime: '昨天'
//   }
// ])

// 当前激活的聊天
const activeChat = computed(() => {
  return chats.value.find(c => c.id === router.currentRoute.value.params.chatId)
})

// 过滤后的聊天列表
const filteredChats = computed(() => {
  return chats.value.filter(chat => 
    chat.name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 打开聊天窗口
const openChat = (chatId) => {
  router.push({
    name: 'ChatSession',
    params: { chatId }
  })
}

// 加载聊天数据（模拟异步）
const loadChats = async () => {
  isLoading.value = true
  // 模拟 API 请求
  setTimeout(() => {
    chats.value = [
      { id: '123', name: '默认聊天'}
    ]
    isLoading.value = false
  }, 500)
}

// 自动打开第一个聊天
const autoOpenChat = () => {
  if (
    !route.params.chatId && 
    !isLoading.value && 
    chats.value.length > 0
  ) {
    router.replace({ // 使用 replace 避免历史记录污染
      name: 'ChatSession',
      params: { chatId: chats.value[0].id }
    })
  }
}

// 初始化
onMounted(async () => {
  await loadChats()
  autoOpenChat()
})

// 监听数据变化
watch([chats, isLoading], autoOpenChat)
</script>

<style scoped>
.chat-home {
  display: flex;
  height: 100vh;
  background: #fff;
}

.chat-list {
  width: 300px;
  border-right: 1px solid #eaeaea;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.list-container {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  padding: 12px;
  cursor: pointer;
  transition: background 0.2s;
  border-bottom: 1px solid #f5f5f5;

  &:hover, &.active {
    background: #f8f8f8;
  }

  .avatar {
    width: 48px;
    height: 48px;
    border-radius: 6px;
    margin-right: 12px;
  }

  .info {
    flex: 1;
    min-width: 0;
  }

  .header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;

    .name {
      font-weight: 500;
      font-size: 15px;
    }

    .time {
      color: #999;
      font-size: 12px;
    }
  }

  .preview {
    color: #666;
    font-size: 13px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.chat-window {
  flex: 1;
  position: relative;
  min-width: 0; /* 防止flex布局溢出 */
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>